package com.fy56.platform.fileupload.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 对指定的路径的文件进行打包，压缩成zip文件
 * Created by li on 2017-12-07.
 */
public class ZipTools {
    /**
     * 把指定路径的文件压缩成zip文件
     *
     * @param dest 文件路径
     * @return
     */
    public static boolean zip(String dest) {
        boolean isZip = false;
        // 如果为目标文件名或者需要压缩文件名为空，则为返回false
        if (dest == null || dest.length() == 0) {
            return false;
        }
        // 如果目标文件名不是以‘zip’结尾，则加上‘zip’后缀
        if (!dest.toLowerCase().endsWith(".zip")) {
            dest = dest + ".zip";
        }
        try {
            File temp = new File(dest);
            File temp2 = new File(temp.getParent());
            if (!temp2.exists()) {
                temp2.mkdir();
            }
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(dest));
            zip(out, temp, "");
            out.close();
            isZip = true;
        }
        catch (Exception e) {
            isZip = false;
        }
        return isZip;
    }

    /**
     * 压缩文件夹或者文件
     *
     * @param out
     * @param f
     * @param base
     * @throws IOException
     */
    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            if (base == "") {
                base = f.getName();
            }
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i].getName());
            }
        } else {
            if (base == "") {
                base = f.getName();
            }
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
        }
    }
}
